#include <cstddef>
#include <vector>
using namespace std;

struct ListNode {
  int val;
  ListNode *next;
  ListNode() : val(0), next(nullptr) {}
  ListNode(int x) : val(x), next(nullptr) {}
  ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
  // 合并两个有序链表
  ListNode *merge2Lists(ListNode *list1, ListNode *list2) {
    if (list1 == nullptr) {
      return list2;
    }
    if (list2 == nullptr) {
      return list1;
    }
    ListNode dummy;
    ListNode *curr = &dummy;

    while (list1 != nullptr && list2 != nullptr) {
      if (list1->val <= list2->val) {
        curr->next = list1;
        list1 = list1->next;
      } else {
        curr->next = list2;
        list2 = list2->next;
      }
      curr = curr->next;
    }
    curr->next = list1 ? list1 : list2;
    return dummy.next;
  }

  ListNode *mergeKLists(vector<ListNode *> &lists) {
    if (lists.empty())
      return nullptr;
    int n = lists.size();
    if (n == 1)
      return lists[0];
    int mid = n / 2;
    // 分治
    vector<ListNode *> left(lists.begin(), lists.begin() + mid);
    vector<ListNode *> right(lists.begin() + mid, lists.end());
    // 归并
    return merge2Lists(mergeKLists(left), mergeKLists(right));
  }
};